package com.bpack;

import com.rest.*;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * LoginActivity
 * Holds the Login Screen.
 * @author Daranhdara Hun
 */
public class LoginActivity extends Activity implements OnClickListener {
	public enum RequestMethod{GET,POST}
	private String errMessage;

	// Create http client
	private BpackConnect client = new BpackConnect("https://p2p.b-pack.com/a/endemo/api3/oauth2/token?");


	// Declare login screen features
	private EditText etUsername;
	private EditText etPassword;
	private Button btnCancel;
	private TextView lblResult;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		/*
		 *  Instantiate the loginButton and set the OnClick Listener
		 */
		View loginButton = findViewById(R.id.login_button);
		loginButton.setOnClickListener(this);
		btnCancel = (Button)findViewById(R.id.cancel_button);
		lblResult = (TextView)findViewById(R.id.result);

		// Preload Paramaters and headers to the client before the request is made
		client.AddParam("grant_type", "password");
		client.AddParam("client_id", "bpackmobile");
		client.AddParam("client_secret", "fe29cbe25949a49f51ed");
		client.AddHeader("content type", "application/x-www-form-urlencoded");

	}

	/** 
	 * onClick
	 * Calls the next activity(view) based on what button is clicked.
	 */
	public void onClick(View v) {
		etUsername = (EditText)findViewById(R.id.username);
		etPassword = (EditText)findViewById(R.id.password);

		// Add user credential to http client once user clicks login button.
		client.AddParam("username", etUsername.getText().toString());
		client.AddParam("password", etPassword.getText().toString());

		// Execute the request
		try{
			client.Execute(RequestMethod.POST);
			errMessage = client.getErrorMessage();
		} catch (Exception e) {
			lblResult.setText("Connection to b-pack app has failed");
			e.printStackTrace();
			Toast.makeText(this, "Connection to b-pack app has failed", 1);
		}

		switch (v.getId()) {
		case R.id.login_button:
			if(!(errMessage.equals("Bad Request"))) {
				// Move on to ToDo List after authentication passes.
				Intent i = new Intent(this, ToDoList.class);
				startActivity(i);
			}
			else 
				lblResult.setText("Authentication Failed"); 
			break;
		}

		// Sets up the cancel button. App is done and should be closed.
		btnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				finish();
			}
		});
	}
}

